package cn.xueden.system.controller;

import cn.xueden.common.group.UserGroup;
import cn.xueden.common.result.Result;
import cn.xueden.system.converter.UserConverter;
import cn.xueden.system.listener.UserImportListener;
import cn.xueden.system.model.dto.UserImportDTO;
import cn.xueden.system.model.form.EditUserForm;
import cn.xueden.system.model.form.UserForm;
import cn.xueden.system.model.vo.UserExcelVO;
import cn.xueden.system.model.vo.UserVO;
import cn.xueden.system.service.IUserService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**功能描述：用户管理控制层
 * @author:梁志杰
 * @date:2025/6/8
 * @description:cn.xueden.system.controller
 * @version:1.0
 */
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {

    private final IUserService userService;

    private final UserConverter userConverter;

    /**
     * 分页获取用户列表数据
     */
    /**
     * 分页获取用户信息
     *
     * @param pageNum  页码
     * @param pageSize 每页记录数
     * @param realName 真实姓名
     * @return 响应结果
     */
    @GetMapping("/paging")
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public Result<IPage<UserVO>> pagingUser(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                                            @RequestParam(value = "realName", required = false) String realName) {
        Page<UserVO> page = new Page<>(pageNum, pageSize);
        return Result.success("获取成功",userService.pagingUser(page, realName));
    }

    /**
     * 创建用户，
     *
     * @param userForm 请求参数，用户名、真实姓名[、角色id]
     * @return 响应结果
     */
    @PostMapping
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public Result<Boolean> createUser(@Validated(UserGroup.CreateUserGroup.class) @RequestBody UserForm userForm) {
        return Result.success("创建用户成功",userService.createUser(userForm)) ;
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public Result<String> updateUser(@RequestBody EditUserForm editUserForm) {
        boolean  result = userService.updateUser(editUserForm);
        return result?Result.success("更新成功"):Result.failed("更新失败");
    }

    /**
     * 批量删除用户
     *
     * @param ids 字符串ids
     * @return 相应结果
     */
    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public Result<String> deleteBatchByIds(@RequestParam("ids") String ids) {
        boolean  result = userService.deleteBatchByIds(ids);
        return result?Result.success("删除成功"):Result.failed("删除失败");
    }

    /**
     * 单个删除接口
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable Long id) {
        boolean  result = userService.deleteById(id);
        return result?Result.success("删除成功"):Result.failed("删除失败");
    }

    /**
     * 导出用户列表数据
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户列表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询数据
        List<UserExcelVO> userList = userService.listForExport();

        // 写入Excel
        EasyExcel.write(response.getOutputStream(), UserExcelVO.class)
                .sheet("用户数据")
                .doWrite(userList);
    }

    /**
     * 导入用户
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public Result importUsers(@RequestParam("file") MultipartFile file) throws IOException {
        UserImportListener listener = new UserImportListener(userService,userConverter);
        EasyExcel.read(file.getInputStream(), UserImportDTO.class, listener)
                .sheet()
                .doRead();

        if (listener.hasError()) {
            return Result.failed("导入失败: " + listener.getErrorMsg());
        }
        return Result.success("导入成功");
    }

    /**
     * 导入模板
     * @param response
     * @throws IOException
     */
    @GetMapping("/template")
    @PreAuthorize("hasAnyAuthority('role_teacher','role_admin')")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户导入模板", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), UserImportDTO.class)
                .sheet("模板")
                .doWrite(ListUtils.newArrayList(new UserImportDTO()));
    }


}
